package com.sjzd.server.config.security;

import com.sjzd.server.exception.YebCommonException;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * @author ZFQ
 * @date 2021/2/21
 */
@Component
public class JwtTokenUtils {
    // 有效载荷claim的名称
    private static final String CLAIM_KEY_USERNAME = "sub";
    // 有效载荷claim的创建时间
    private static final String CLAIM_KEY_CREATED = "created";
    // jwt令牌密匙
    @Value("${jwt.secret}")
    private String secret;
    //jwt令牌有效时间
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     *  根据用户信息生成token
     * @param userDetails
     * @return
     */
    public String createTokenByUser(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return doCreateToken(claims);
    }

    /**
     *  根据载荷生成token
     * @param claims
     * @return
     */
    private String doCreateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(createExpiration(expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     *  生成token的过期时间
     * @param expiration
     * @return
     */
    private Date createExpiration(Long expiration) {
       return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     *  验证token是否有效
     * @param token
     * @param userDetails
     * @return
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        if (!StringUtils.hasText(username)) {
            throw new YebCommonException("请先登录系统！");
        }
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     *  判断token是否已经过期
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        Date expiration = getExpirationFromToken(token);
        if (null == expiration) {
            throw new YebCommonException("token已过期,请重新登录！");
        }
        return expiration.getTime() < System.currentTimeMillis();
    }

    /**
     *  获取token的过期时间
     * @param token
     * @return
     */
    private Date getExpirationFromToken(String token) {
        Date expiration = null;
        try {
            Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            return null;
        }
        return expiration;
    }

    /**
     *  从token中获取用户名
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token) {
        String username = null;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return username;
    }

    /**
     *  从token中获取载荷信息
     * @param token
     * @return
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
     *  刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return doCreateToken(claims);
    }

    /**
     *  判断是否需要刷新token
     * @param token
     * @return
     */
    public boolean needFreshToken(String token) {
        return isTokenExpired(token);
    }
}

